import { getToken, setToken, setSStorage } from '@/utils/auth'
import user from '@/apis/user'
import { getLanguage, setLanguage } from '@/lang'

const state = {
  token: getToken(), // token
  userInfo: '', // 登录用户信息
  language: getLanguage(), // 语言
  iframe: false// 是否为iframe
}

const mutations = {
  SET_USERINFO(state, data) {
    state.userInfo = data
  },
  CLEAR_USERINFO(state) {
    state.userInfo = ''
  },
  SET_TOKEN(state, token) {
    state.token = token
    setToken(token)
  },
  SET_LANGUAGE: (state, language) => {
    state.language = language
    setSStorage('language', language)
  },
  SET_IFAMRE: (state, iframe) => {
    state.iframe = iframe
  }
}

const actions = {
  // 登录
  Login({ commit }, data) {
    const { email, password } = data
    return new Promise((resolve, reject) => {
      try {
        user.login({ email: email, password: password }).then(res => {
          commit('SET_TOKEN', res)
          resolve()
        })
      } catch (err) {
        reject(err)
      }
    })
  },
  // 钉钉登录
  ddLogin({ commit }, data) {
    return new Promise((resolve, reject) => {
      user.ddLogin(data).then(response => {
        commit('SET_TOKEN', response)
        setToken(response)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 获取用户信息
  GetUserInfo({ commit }) {
    return new Promise((resolve, reject) => {
      user.getInfo().then(
        res => {
          commit('SET_USERINFO', res)
          resolve(res)
        },
        err => {
          reject(err)
        }
      )
    })
  },
  // 登出
  Loginout({ commit }) {
    return new Promise((resolve, reject) => {
      try {
        commit('CLEAR_USERINFO')
        commit('CLEAR_FAMILY_OPTIONS')
        commit('SET_TOKEN', '')
        resolve()
      } catch (err) {
        reject(err)
      }
    })
  },
  // 设置语言
  SetLanguage({ commit }, language) {
    return new Promise((resolve, reject) => {
      try {
        setLanguage(language)
        commit('SET_LANGUAGE', language)
        resolve()
      } catch (err) {
        reject(err)
      }
    })
  },
  // 设置语言
  SetIframe({ commit }, status) {
    return new Promise((resolve, reject) => {
      try {
        commit('SET_IFAMRE', status)
        resolve()
      } catch (err) {
        reject(err)
      }
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
